const express = require("express");
const { Chapter, Course } = require("../../models");
const router = express.Router();
const Sequelize = require("sequelize");
const { NotFoundError } = require("../../utils/errors");
const { success, failure } = require("../../utils/responses");
const Op = Sequelize.Op;

/**
 * 获取章节列表
 * GET /admin/chapters
 */
router.get("/", async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;
    if (!query.courseId) {
      throw new Error("获取章节列表失败，课程ID不能为空。");
    }
    const condition = {
      ...getCondition(),
      order: [
        ["rank", "ASC"],
        ["id", "ASC"],
      ],
      offset,
      limit: pageSize,
    };
    condition.where = {
      courseId: {
        [Op.eq]: query.courseId,
      },
    };
    if (query.title) {
      condition.where = {
        title: {
          [Op.like]: `%${query.title}%`,
        },
      };
    }
    const chapters = await Chapter.findAndCountAll(condition);
    success(res, "Get chapters successfully", {
      chapters: chapters.rows,
      total: chapters.count,
      currentPage,
      pageSize,
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 根据id获取章节
 * GET /admin/chapters/:id
 */
router.get("/:id", async function (req, res) {
  try {
    const chapter = await getChapter(req);
    success(res, "Get chapter successfully", { chapter });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建章节
 * POST /admin/chapters
 */
router.post("/", async function (req, res) {
  try {
    const body = filterBody(req.body);
    const chapter = await Chapter.create(body);
    success(res, "Create chapter successfully", { chapter }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除章节
 * DELETE /admin/chapters/:id
 */
router.delete("/:id", async function (req, res) {
  try {
    const chapter = await getChapter(req);
    await chapter.destroy();
    success(res, "Delete chapter successfully");
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新章节
 * PUT /admin/chapters/:id
 */
router.put("/:id", async function (req, res) {
  try {
    const chapter = await getChapter(req);
    await chapter.update(filterBody(req.body));
    success(res, "Update chapter successfully", { chapter });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 公共方法： 获取关联查询条件
 */
function getCondition() {
  return {
    attributes: { exclude: ["courseId"] },
    include: [{ model: Course, as: "course", attributes: ["id", "name"] }],
  };
}

/**
 * 公共方法： 过滤请求体
 */
function filterBody(body) {
  const { courseId, title, content, video, rank } = body;
  return {
    courseId,
    title,
    content,
    video,
    rank,
  };
}

/**
 * 公共方法： 查询当前章节
 */
async function getChapter(req) {
  const { id } = req.params;
  const condition = getCondition();
  const chapter = await Chapter.findByPk(id, condition);
  if (!chapter) {
    throw new NotFoundError(`ID: ${id}的章节未找到`);
  }
  return chapter;
}

module.exports = router;
